package com.movie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageInfo;
import com.movie.bean.*;
import com.movie.bean.vo.TicketOrderQueryVO;
import com.movie.common.HttpResult;
import com.movie.service.MovieService;
import com.movie.service.UserService;
import com.movie.utils.FileUpload;
import com.obs.services.ObsClient;
import com.obs.services.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
public class MovieController {

    @Autowired
    private FileUpload fileUpload;
    private static final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Autowired
    private MovieService movieService;


    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private UserService userService;

    @GetMapping("/MovieSeat")
    @ResponseBody
    public Map<String, Object> getMovieSeat(int sid) {
        Map<String, Object> map = new HashMap<>();
        map.put("seat", movieService.getSeat(sid));
        map.put("session", movieService.getSession(sid));
        return map;
    }

    @PostMapping("/BuyTicket")
    @ResponseBody
    public Map<String, Object> buyTicket(@RequestBody List<Ticket> tickets) {
        Map<String, Object> map = new HashMap<>();
        if (movieService.checkTicket(tickets).size() == 0) {
            int userId = tickets.get(0).getUseid();
            int sessionId = tickets.get(0).getSessionid();
            String number = tickets.get(0).getNumber();
            String key = "order:" + userId + ":number:" + number;
            redisTemplate.opsForValue().set(key, tickets);
            redisTemplate.expire(key, 900, TimeUnit.SECONDS);
            for (Ticket ticket : tickets) {
                key = "session:" + sessionId + ":number:" + number + ":seat:" + ticket.getSeat();
                redisTemplate.opsForValue().set(key, ticket.getSeat());
                redisTemplate.expire(key, 900, TimeUnit.SECONDS);
            }
//            movieService.buyTicket(tickets);
            map.put("isSuccess", true);
            map.put("message", "订单提交成功!");
        } else {
            map.put("isSuccess", false);
            map.put("message", "该位置有人了哦!");
        }
        return map;
    }

    @PostMapping("returnTicket/{number}/{uid}")
    public HttpResult<?> returnTicket(@PathVariable("number") String number, @PathVariable("uid") Integer uid) {
        movieService.returnTicket(number, uid);
        return HttpResult.success(userService.getUserByUid(uid));
    }


    @GetMapping(value = {"/UserHomePage", "GetAllMovieList"})
    @ResponseBody
    public List<Movie> getAllMovieList() {
        return movieService.getAllMovieList();
    }

    @GetMapping("/MovieSessionList")
    @ResponseBody
    public List<Session> getMovieSessionList(int mid) {
        return movieService.getMovieSessionList(mid);
    }

    @GetMapping("/page/{pageNum}/{pageSize}")
    @ResponseBody
    public Page<Movie> getStuPageInfo(@PathVariable int pageNum, @PathVariable int pageSize) {
        return movieService.getMovieListPageInfo(pageNum, pageSize);
    }

    @PostMapping("/DeleteMovie")
    @ResponseBody
    public void DelMovieServlet(int mid) {
        movieService.delMovieByMid(mid);
    }

    @PostMapping("/MovieEdit")
    @ResponseBody
    public void movieEdit(Movie movie, MultipartFile img) {
        movieService.updateMovie(movie, img);
    }

    @PostMapping("/AddMovieSession")
    @ResponseBody
    public void addMovieSession(@RequestBody Session session) {
        session.setStatus(0);
        movieService.addMovieSession(session);
    }


    @GetMapping("/GetChartData")
    @ResponseBody
    public Map<String, Object> getChartData() {
        Map<String, Object> map = new HashMap<>();
        map.put("movieRankList", movieService.getMovieRankList());
        map.put("totalMoney", movieService.gerTotalMoney());
        map.put("userCount", movieService.getUserCount());
        map.put("adminCount", movieService.getAdminCount());
        map.put("movieCount", movieService.getMovieCount());
        map.put("ticketCount", movieService.getTicketCount());
        map.put("rechargeCount", movieService.getRechargeCount());
        map.put("rechargeRecent", movieService.getRechargeRecent());
        return map;
    }

    @PostMapping("/SlideImgUpload")
    @ResponseBody
    public HttpResult<?> slideImgUpload(MultipartFile img, int mid, Integer id) {
        if (img != null) {
            String fileName = fileUpload.upload(img);
            if (id == null) {
                movieService.addSlideImg(mid, fileName, df.format(new Date()));
            } else {
                movieService.updateSlideImg(mid, fileName,id);
            }
        } else {
            movieService.updateSlideImg1(mid,id);
        }
        return HttpResult.success();
    }

    @GetMapping("/GetSlideImg")
    @ResponseBody
    public List<SlideImg> getSlideImg() {
        return movieService.getSlideImgList();
    }

    @GetMapping("/slideImgDetail/{id}")
    @ResponseBody
    public HttpResult<SlideImg> slideImgDetail(@PathVariable("id") Integer id) {
        return HttpResult.success(movieService.slideImgDetail(id));
    }


    @GetMapping("/GetMovieListByKeyWord")
    @ResponseBody
    public List<Movie> getMovieListByKeyWord(String keyWord) {
        return movieService.getMovieListByKeyWord(keyWord);
    }

    @GetMapping("/GetTicketOrderList/{pageNum}/{pageSize}")
    @ResponseBody
    public Page<TicketOrder> getTicketOrderList(@PathVariable int pageNum, @PathVariable int pageSize) {
        return movieService.getTicketOrderList(pageNum, pageSize);
    }

    @PostMapping("/GetTicketOrderByKeyWord")
    @ResponseBody
    public Page<TicketOrder> getTicketOrderByKeyWord(@RequestBody TicketOrderQueryVO ticketOrderQueryVO) {
        return movieService.getTicketOrderByKeyWord(ticketOrderQueryVO);
    }

    @PostMapping("/DelSlideImgById")
    @ResponseBody
    public void delSlideImgById(int id) {
        movieService.delSlideImgById(id);
    }

    @GetMapping("/GetHotMovieList")
    @ResponseBody
    public List<Movie> getHotMovieList() {
        return movieService.getHotMovieList();
    }

    @GetMapping("/GetHotMovieByKeyWord")
    @ResponseBody
    public List<Movie> getHotMovieByKeyWord(String mclass, String mnation) {
        return movieService.getHotMovieByKeyWord(mclass, mnation);
    }

    @GetMapping("/GetMovieRankList")
    @ResponseBody
    public List<MovieRank> getMovieRankList() {
        return movieService.getMovieRankList();
    }

    @GetMapping("/GetMovieSearchResult")
    @ResponseBody
    public List<Movie> getMovieSearchResult(String searchType, String searchContent) {
        System.out.println(searchType + " " + searchContent);
        return movieService.getMovieSearchResult(searchType, searchContent);
    }

    @GetMapping("/getLikeMovie")
    @ResponseBody
    public HttpResult<PageInfo<Favorite>> getLikeMovie(Integer id, Integer pageNo, Integer pageSize) {
        return HttpResult.success(movieService.getLikeMovie(id, pageNo, pageSize));
    }

    @GetMapping("/t2")
    public HttpResult<?> t2(String a){
        return HttpResult.success(a);
    }
}
